package level4.display
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;

	/**
	 * 有统计功能的Loader
	 * */
	public class StatisticsLoader extends Loader
	{
		//总长度
		public var totalLen:uint;
		//上次下载的长度
		private var lastLen:uint;
		//2次长度的差
		private var lenDiff:uint;
		
		private var loadingNotifyFun:Function;
		
		public function StatisticsLoader()
		{
			contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onStatisticsProgress);
			contentLoaderInfo.addEventListener(Event.COMPLETE,onOk);
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIoError);
		}
		///////////////////////
		//事件
		///////////////////////
		private function onStatisticsProgress(e:ProgressEvent):void{
			if(totalLen == 0){
				totalLen = e.bytesTotal;
			}
			//contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,onStatisticsProgress);
			lenDiff = e.bytesLoaded - lastLen;
			lastLen += lenDiff;
			if(loadingNotifyFun != null){
				loadingNotifyFun(lenDiff);
			}
		}
		private function onOk(e:Event):void{
			dispose();
		}
		private function onIoError(e:IOErrorEvent):void{
			dispose();
		}
		private function dispose():void{
			contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,onStatisticsProgress);
			contentLoaderInfo.removeEventListener(Event.COMPLETE,onOk);
			contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onIoError);
			loadingNotifyFun = null;
		}
		/**
		 * 获取 当前下载文件的总长度.
		 * 如果还不能获取就等待.
		 * @param callback,格式为 function(curTotalLen:uint):void
		 * 当当前总长度获取到后,将调用callback,并将当前的总长度放入第一个参数.
		 * */
		public function getTotalLenWhileCanGetIt(callback:Function):void{
			var timerId:int = setInterval(function():void{
				if(totalLen != 0){
					clearInterval(timerId);
					callback(totalLen);
				}
			},100);
		}
		/**
		 * 获取 当前下载的字节数.
		 * 并不是当前已下载的字节数.是2次下载的字节数之差
		 * callback格式为:function(curLen:uint):void
		 * 当前长度会,填充进curLen变量.外部来获取并统计
		 * */
		public function setLoadingNotify(callback:Function):void{
			this.loadingNotifyFun = callback;
		}
		
	}
}